package org.weso.lodin.datasource.config;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.util.LinkedList;
import java.util.List;

import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.weso.lodin.dao.PrimaryObservationDAOImpl;
import org.weso.lodin.exceptions.LodinModelException;
import org.weso.lodin.generated.Dataset;
import org.weso.lodin.generated.IdIndicator;
import org.weso.lodin.generated.TypeTable;
import org.weso.lodin.generated.TypeValues;
import org.weso.lodin.utils.POIUtils;


public class DatasetTemplateDAOPrimaryImpl implements DatasetTemplateDAO {

	private HSSFWorkbook wb;
	private List<Dataset> datasets;
	
	protected static Logger logger = Logger.getLogger(DatasetTemplateDAOPrimaryImpl.class);

	public DatasetTemplateDAOPrimaryImpl(InputStream data){
		try {			
			this.wb = new HSSFWorkbook(data);
		} catch (IOException e) {
			throw new LodinModelException(e, "Loading workbook "+this.getClass().getName());
		}
	}

	
	private List<Dataset> createDatasets(HSSFWorkbook wb, String dataType) {
		List<Dataset> datasets = new LinkedList<Dataset>();
		try {	
		
			HSSFSheet sheet = wb.getSheet(dataType);
			HSSFRow row = sheet.getRow(0);
			int physicalNumberOfCells = row.getPhysicalNumberOfCells();
			System.out.println(dataType+" "+physicalNumberOfCells);
			//FIXME: new data is loaded from 1 not 0
			for(int i = 1; i<physicalNumberOfCells;i++){
				String extractValue = POIUtils.extractValue(row.getCell(i));
				if(extractValue.length()>0){									
					String indicator = extractValue.split("-")[0].trim();
					//String indicator = extractValue;
					if(indicator.contains("&")){
						//FIXME: SKIP-Q9B and Q9D
						String indicator1 = indicator.split("&")[0].trim();
						String trim = indicator.split("&")[1].trim();
						String hackIndicator = indicator1+trim.charAt(trim.length()-1);
						datasets.add(createDataset(i, hackIndicator, dataType));
						logger.info("Adding dataset from indicator: "+hackIndicator);
					}else{
						datasets.add(createDataset(i, indicator, dataType));
						logger.info("Adding simple dataset from indicator: "+indicator);
					}								
				}				
			}			
		} catch (DatatypeConfigurationException e) {
			throw new LodinModelException(e, "Datatype Configuration Exception");
		}
		return datasets;
	}


	public List<Dataset> getDatasets() {
		if(this.datasets == null){
			logger.info("Loading raw primary datasets");
			this.datasets = createDatasets(this.wb, PrimaryObservationDAOImpl.RAW_DATA_PRIMARY);
			logger.info("Loading normalised primary datasets");
			this.datasets.addAll(createDatasets(this.wb, PrimaryObservationDAOImpl.NORMALISED_DATA_PRIMARY));
		}		
		return this.datasets;
	}


	public static Dataset createDataset(int row, String indicator, String dataType) throws DatatypeConfigurationException{
		Dataset currentDataset = new Dataset();	
		System.out.println(indicator);
		currentDataset.setId(IdIndicator.fromValue(indicator).value()+"-"+dataType);//sheet-name
		currentDataset.setIndicator(IdIndicator.fromValue(indicator));
		TypeTable typeTable = new TypeTable();	
		typeTable.setRowStart(new BigInteger("3")); //constant
		typeTable.setRowEnd(new BigInteger("63"));//constant
		TypeValues values = new TypeValues();
		values.setCountryCol("A"); //constant
		values.setValueCol(""+row);
		values.setYear(DatatypeFactory.newInstance().newXMLGregorianCalendar("2011"));//constant
		values.setDatatype("number");
		typeTable.getValues().add(values);
		currentDataset.getTable().add(typeTable );
		return currentDataset;
	}
	

}
